package com.csi.utils;

import com.csi.domain.User;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 二维码生成工具包
 */
public class CreateQR {

    public static boolean generateQRCode(String content, String path) throws WriterException, IOException {
        int width = 200; // 二维码图片宽度
        int height = 200; // 二维码图片高度
        String format = "png"; //保存图片的格式
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");//字符集
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //容错率
        hints.put(EncodeHintType.MARGIN, 2); //外边距

        // 生成二维码
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            //文件路径
            Path path1 = new File(path).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix,format,path1);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}